package com.kongt.service.impl;

import com.kongt.domain.Kv;
import com.kongt.domain.KvRepository;
import com.kongt.model.KvPageable;
import com.kongt.model.KvSearchModel;
import com.kongt.model.PageModel;
import com.kongt.service.KvService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.xml.bind.ValidationException;

@Service
public class KvServiceImpl implements KvService {
    /**
     * key值存在
     */
    public final static String KV_KEY_EXSITS = "key已经存在";

    /**
     * id所在对象不存在
     */
    public final static String KV_ID_OBJECT_NOT_EXSITS = "当前提交的id的对象不存在！";

    /**
     * id必须输入
     */
    public final static String KV_ID_MUST_INPUT = "id必须传入！";

    @Autowired
    private KvRepository kvRepository;

    public Kv save(Kv entity) throws ValidationException {
        if (entity.getId() == null) {
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("key", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withIgnorePaths("id", "value");

            if (kvRepository.exists(Example.of(entity, matcher))) {
                throw new ValidationException(KV_KEY_EXSITS);
            }
        } else {
            ExampleMatcher matcher = ExampleMatcher.matchingAll()
                    .withIgnorePaths("key", "value");
            if (!kvRepository.exists(Example.of(entity, matcher))) {
                throw new ValidationException(KV_ID_OBJECT_NOT_EXSITS);

            }
            matcher = ExampleMatcher.matchingAll()
                    .withIgnorePaths("id", "value");
            if (kvRepository.exists(Example.of(entity, matcher))) {
                throw new ValidationException(KV_KEY_EXSITS);
            }
        }
        return kvRepository.save(entity);

    }

    public void deleteById(Long id) {
        kvRepository.deleteById(id);
    }

    public PageModel<Kv> list(KvSearchModel search) {
        PageModel pmodel = new PageModel<Kv>();
        search.setAsc(false);
        search.setSortFiled("id");
        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withIgnorePaths("id")
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        Example<Kv> example = Example.of(new Kv(null, search.getKeyword(), search.getKeyword()), matcher);
        Page<Kv> pageKv = kvRepository.findAll(example, new KvPageable(search));
        pmodel.setCount(pageKv.getTotalElements());
        pmodel.setRows(pageKv.getContent());
        return pmodel;
    }

    public Kv getOne(Long id) {
        return kvRepository.getOne(id);
    }
}
